<?php

namespace app\api\service;

use app\common\cache\SmsVerifyCache;
use tmcore\base\BaseService;
use tmcore\exceptions\ValidateException;
use tmcore\services\notice\NoticeService;

class CaptchaService extends BaseService
{
    /**
     * 发送短信验证码
     * @param $params
     * @return bool
     */
    public static function sendSmsCode($params) {
        try {
            $code = com_random(6, '0123456789');
            $res = NoticeService::send($params['scene'], [
                'sms' => [
                    'mobile' => $params['mobile'],
                    'template' => [
                        'code' => $code
                    ]
                ]
            ]);
            if(!$res) throw new ValidateException(NoticeService::getError());

            (new SmsVerifyCache)->setSmsCode($code, $params['mobile'], $params['scene']);

            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }
}